package com.unionftech.crm_android;

import android.content.Intent;
import android.content.IntentFilter;
import android.text.TextUtils;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.launcher.ARouter;
import com.unionftech.baselibrary.base.BaseApplication;
import com.unionftech.baselibrary.glide.core.ImageOptions;
import com.unionftech.baselibrary.network.RetrofitClient;
import com.unionftech.common.CommonConstants;
import com.unionftech.common.CommonInit;
import com.unionftech.common.network.SimpleNetWork;
import com.unionftech.common.recaptcha.RecaptchaInterceptor;
import com.unionftech.common.recaptcha.RecaptchaUtil;
import com.unionftech.common.router.service.ILoginService;
import com.unionftech.common.utils.ChangeDevUtil;
import com.unionftech.common.utils.LogUtils;
import com.unionftech.common.utils.SpUtils;
import com.unionftech.content_login.api.interceptor.ITokenRefresh;
import com.unionftech.content_login.api.interceptor.TokenRefreshInterceptor;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Interceptor;

public class App extends BaseApplication {
    private static App app;
    private LocaleChangeReceiver localeChangeReceiver;
    @Autowired
    ILoginService mLoginService;

    @Override
    public void onCreate() {
        super.onCreate();
        app = this;
        // 注册广播接收器
        registerLocaleChangeReceiver();
        initSdk();
        initModule();
    }

    private void registerLocaleChangeReceiver() {
        localeChangeReceiver = new LocaleChangeReceiver();
        IntentFilter filter = new IntentFilter(Intent.ACTION_LOCALE_CHANGED);
        registerReceiver(localeChangeReceiver, filter);
    }

    private void initSdk() {
        //初始化Common
        boolean isDebug = !BuildConfig.PROD || isDebug();
        CommonInit.getInstance().init(app, isDebug);
        //初始化google
        RecaptchaUtil.getInstance().init(app);
//        //设置图片加载的默认占位图
//        ImageOptions.DrawableOptions.setDefault(drawableOptions -> {
//            //加载占位图
//            drawableOptions.setPlaceHolderResId(R.drawable.ic_launcher_background);
//            //错误占位图
//            drawableOptions.setErrorResId(R.drawable.ic_launcher_foreground);
//            //url空白占位图
//            drawableOptions.setFallbackResId(R.drawable.ic_launcher_foreground);
//            return null;
//        });
    }

    private void initModule() {
        //初始化module
        ARouter.getInstance().inject(this);
        initRetrofit();
    }

    private void initRetrofit() {
        ArrayList<Interceptor> interceptors = new ArrayList<>();
        //滑块验证拦截器
        RecaptchaInterceptor recaptchaInterceptor = new RecaptchaInterceptor();
        //自动刷新用户token的拦截器
        TokenRefreshInterceptor tokenRefreshInterceptor = new TokenRefreshInterceptor((ITokenRefresh) mLoginService);
        interceptors.add(recaptchaInterceptor);
        interceptors.add(tokenRefreshInterceptor);
        SimpleNetWork netWork = new SimpleNetWork(initUrlMap(), interceptors);
        RetrofitClient.init(netWork);
    }

    private Map<String, String> initUrlMap() {
        Map<String, String> map = new HashMap<>();
        String curBaseUrl = SpUtils.getInstance().getString(CommonConstants.Key.KEY_CURRENT_BASE_URL);
        String appBuildTime = SpUtils.getInstance().getString(CommonConstants.Key.KEY_APP_BUILD_TIME);
        if (!TextUtils.equals(appBuildTime, BuildConfig.INSTALL_TIME)) {
            SpUtils.getInstance().remove(CommonConstants.Key.KEY_CURRENT_BASE_URL);
            curBaseUrl = "";
        }
        String initUrl = UrlConfig.TEST_BASE_URL;
        //release上线的情况下，不开启环境切换
        if (BuildConfig.PROD) {
            initUrl = UrlConfig.RELEASE_BASE_URL;
        } else {
            ChangeDevUtil.initChangeBaseUrlList(UrlConfig.INSTANCE.getMAP_URL());
        }
        //网络请求的baseUrl
        map.put(RetrofitClient.KEY_BASE_URL, TextUtils.isEmpty(curBaseUrl) ? initUrl : curBaseUrl);
        //国际化请求的assetsUrl
        map.put(CommonConstants.Key.KEY_ASSETS_URL, UrlConfig.BASE_ASSETS_URL);
        LogUtils.d("App", "当前App的环境：" + map.toString());
        return map;
    }


    @Override
    public void onTerminate() {
        super.onTerminate();
        CommonInit.getInstance().destroy();
        // 取消注册广播接收器
        if (localeChangeReceiver != null) {
            unregisterReceiver(localeChangeReceiver);
        }
    }
}
